package com.bishe.app.core.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bishe.app.core.utils.AppRunnerUtils;
import com.bishe.app.modules.user.entity.User;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Slf4j
public class SessionInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @SneakyThrows
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //认证
        User userFromToken = getUserFromToken();
        if (userFromToken == null) {
            toLogin(response);
            log.error("拦截拦截路径:{}", request.getRequestURI());
            return false;
        }
        request.setAttribute("CUR_USER", userFromToken);
        log.info("CURR_USER:{},URI:{}", JSON.toJSONString(userFromToken), request.getRequestURI());
        return true;
    }

    public User getUserFromToken() {
        String token = AppRunnerUtils.getHeader("X-Token");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        String userStr = redisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(userStr) || userStr == null || userStr.isEmpty()) {
            return null;
        }
        return JSON.parseObject(userStr, User.class);
    }

    private static void toLogin(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
//        response.setStatus(HttpStatus.FORBIDDEN.value());
        JSONObject res = new JSONObject();
        res.put("data", null);
        res.put("code", "403");
        res.put("message", "访问无权限-拦截");
        PrintWriter out = response.getWriter();
        out.append(res.toString());
    }


}